import React, { useState, useRef, useEffect } from 'react';
import {
  ModalForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
  ProFormGroup,
  ProFormList,
  ProFormDependency,
  ProTable,
  ProCard,
} from '@ant-design/pro-components';
import { Button, Tag, message, Upload } from 'antd';

import type { ProFormInstance } from '@ant-design/pro-components';
import type { UploadProps } from 'antd';

import { useRequest } from 'umi';
import moment from 'moment';

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

const Plan = ({ stageId, PlanData, refreshMyOverview }: any) => {
  const editPlanRef = useRef<ProFormInstance>();
  // 上传材料文件
  const props: UploadProps = {
    name: 'material',
    action: 'http://10.1.40.84:9998/stuTrain/uploadMaterial',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    // showUploadList: false,
  };
  //学生端——获取个人学习计划列表
  const getMyPlanList = useRequest(() => {
    return {
      url: `http://10.1.40.84:9998/stuTrain/getMyPlanList?stageId=${stageId}`,
      method: 'GET',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
    };
  });
  useEffect(() => {
    getMyPlanList.run();
  }, [PlanData, stageId]);

  //学生端——查看我的一个计划详细内容
  const getMyOnePlan = useRequest(
    (id = null) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/getMyOnePlan?id=${id}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      manual: true,
    },
  );
  //更新计划
  const updatePlanAndMaterial = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9998/stuTrain/updatePlanAndMaterial`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
      // onSuccess: () => {
      //     getMyOverview.run();
      // },
    },
  );
  const columns = [
    {
      title: '计划名称',
      dataIndex: 'planName',
      key: 'planName',
      // hideInSearch: true,
    },
    {
      title: '计划所属阶段',
      dataIndex: 'stageName',
      key: 'stageName',
      render: (text: any) => <Tag color={'blue'}>{text}</Tag>,
    },
    {
      title: '计划状态',
      dataIndex: 'planState',
      key: 'planState',
      render: (text: any) => {
        if (text === '已完成') {
          return <Tag color={'blue'}>{text}</Tag>;
        } else {
          return <Tag color={'gold'}>{text}</Tag>;
        }
      },
    },
    {
      title: '计划开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      render: (text: any) => moment(text).format('YYYY-MM-DD'),
    },
    {
      title: '计划终止时间',
      dataIndex: 'endTime',
      key: 'endTime',
      render: (text: any) => moment(text).format('YYYY-MM-DD'),
    },
    // {
    //   title: '查阅导师',
    //   dataIndex: '查阅导师',
    // },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      align: 'center',
      render: (text: any, record: any) => [
        <ModalForm
          key="1"
          title="查看计划"
          trigger={
            <Button
              size="small"
              type="link"
              onClick={() => {
                getMyOnePlan.run(record.id).then((e) => {
                  editPlanRef.current?.setFieldsValue(e[0]);
                });
              }}
            >
              查看计划
            </Button>
          }
          autoFocusFirstInput
          modalProps={{
            onCancel: () => console.log('run'),
            destroyOnClose: true,
          }}
          submitTimeout={2000}
          onFinish={async (values) => {
            await waitTime(2000);
            updatePlanAndMaterial.run(values).then(() => {
              getMyPlanList.run();
              refreshMyOverview();
              message.success('修改成功！');
            });
            return true;
          }}
          formRef={editPlanRef}
          submitter={{
            searchConfig: {
              submitText: '提交',
              resetText: '取消',
            },
            render: (props, defaultDoms) => {
              // console.log(props);
              if (record.planState === '已完成') {
                return null;
              } else {
                return [...defaultDoms];
              }
            },
          }}
        >
          <ProForm.Group>
            <ProFormText
              width="md"
              name="id"
              hidden
              disabled={record.planState === '已完成'}
            />
            <ProFormText
              width="md"
              name="planName"
              label="计划名称"
              required
              disabled={record.planState === '已完成'}
            />
            <ProFormText
              width="md"
              name="planDesc"
              label="计划描述"
              required
              disabled={record.planState === '已完成'}
            />
            <ProFormDatePicker
              width="sm"
              name="startTime"
              label="计划开始时间"
              required
              disabled={record.planState === '已完成'}
            />
            <ProFormDatePicker
              width="sm"
              name="endTime"
              label="计划终止时间"
              required
              disabled={record.planState === '已完成'}
            />
            <ProFormSelect
              label="材料共享"
              name="isShareable"
              width="xs"
              valueEnum={{
                '1': '共享',
                '0': '不共享',
              }}
              required
              disabled={record.planState === '已完成'}
            />
          </ProForm.Group>
          <ProFormList
            name="materialList"
            label="材料信息"
            rules={[
              {
                validator: async (_, value) => {
                  // console.log(value);
                  if (value && value.length > 0) {
                    return;
                  }
                  throw new Error('至少要有一项！');
                },
              },
            ]}
            creatorButtonProps={{
              creatorButtonText: '添加材料',
              hidden: record.planState === '已完成',
            }}
            copyIconProps={
              record.planState === '已完成' ? false : { tooltipText: '复制' }
            }
            deleteIconProps={
              record.planState === '已完成' ? false : { tooltipText: '删除' }
            }
          >
            {(meta: any, index: any, action: any, count: any) => {
              return (
                <ProFormGroup key="group">
                  <ProFormText
                    width="sm"
                    required
                    name="materialName"
                    label="材料名称"
                    disabled={record.planState === '已完成'}
                  />
                  <ProFormSelect
                    label="材料类型"
                    name="materialType"
                    width="xs"
                    required
                    valueEnum={{
                      学习报告: '学习报告',
                      参考文献: '参考文献',
                    }}
                    disabled={record.planState === '已完成'}
                  />
                  <ProFormDependency name={['materialType']}>
                    {({ materialType }) => {
                      if (materialType === '参考文献') {
                        return (
                          <ProFormText
                            width="sm"
                            name="materialContent"
                            label="文献链接"
                            required
                            // disabled={record.planState === "已完成"}
                          />
                        );
                      } else if (
                        materialType === '学习报告' ||
                        materialType === '阶段性报告'
                      ) {
                        return (
                          <>
                            <Upload
                              {...props}
                              onChange={(info) => {
                                if (info.file.status === 'done') {
                                  action.setCurrentRowData({
                                    materialContent: info.file.response.data,
                                  });
                                  message.success(
                                    `${info.file.name} 上传成功！`,
                                  );
                                } else if (info.file.status === 'error') {
                                  message.error(
                                    `${info.file.name} file upload failed.`,
                                  );
                                  //  disabled={record.planState === "已完成"}
                                }
                              }}
                            >
                              <Button
                                type="link"
                                style={
                                  index === 0
                                    ? { marginTop: 30 }
                                    : { marginTop: 0 }
                                }
                                disabled={record.planState === '已完成'}
                              >
                                上传材料
                              </Button>
                            </Upload>

                            <ProFormText
                              width="sm"
                              name="materialContent"
                              required
                              hidden
                              disabled={record.planState === '已完成'}
                            />
                          </>
                        );
                      } else {
                        return null;
                      }
                    }}
                  </ProFormDependency>
                  <ProFormDependency name={['materialType']}>
                    {({ materialType }) => {
                      if (
                        materialType === '学习报告' &&
                        action.getCurrentRowData().materialContent
                      ) {
                        return (
                          <Button
                            type={'link'}
                            style={
                              index === 0 ? { marginTop: 30 } : { marginTop: 0 }
                            }
                            onClick={() => {
                              window.open(
                                action.getCurrentRowData().materialContent,
                              );
                            }}
                            // disabled={record.planState === "已完成"}
                          >
                            下载
                          </Button>
                        );
                      } else {
                        return null;
                      }
                    }}
                  </ProFormDependency>
                </ProFormGroup>
              );
            }}
          </ProFormList>
        </ModalForm>,
        <Button
          key="2"
          type="link"
          size="small"
          disabled={record.planState === '已完成'}
          onClick={() => {
            getMyOnePlan.run(record.id).then((e) => {
              updatePlanAndMaterial.run({ ...e[0], planState: 1 }).then(() => {
                getMyPlanList.run();
                message.success('确认完成！');
              });
            });
          }}
        >
          确认完成
        </Button>,
      ],
    },
  ];
  return (
    <ProTable
      columns={columns}
      dataSource={getMyPlanList?.data || []}
      rowKey="id"
      search={false}
      options={false}
      pagination={{
        pageSize: 5,
        hideOnSinglePage: true,
      }}
      dateFormatter="string"
    />
  );
};

export default Plan;
